import React from 'react';
import { ProForm, ProFormText, ProFormSelect, ProFormDigit, ProFormList, ProFormGroup } from '@ant-design/pro-components';
import { message } from 'antd';
import { useRequest } from 'umi';
import { createAuditConfig, updateAuditConfig } from '@/services/ant-design-pro/audit'; // Assume these services are defined

const AuditConfigForm: React.FC = ({ initialValues, isEditMode, onClose, onSuccess, user, role }) => {
  const { run } = useRequest((values) => (isEditMode ? updateAuditConfig({id:initialValues.id,...values}) : createAuditConfig(values)), {
    manual: true,
    onSuccess: () => {
      message.success(isEditMode ? '更新成功' : '创建成功');
      onClose();
      onSuccess();
    },
    onError: () => {
      console.log(isEditMode ? '更新失败' : '创建失败');
    },
  });

  // 处理 initialValues 中的 roleCode
  const processedInitialValues = React.useMemo(() => {
    if (initialValues) {
      const roleCodes = initialValues?.roleCode ? initialValues.roleCode.split(',') : [];
      const sendCode  = initialValues?.sendCode ? initialValues.sendCode.split(',') : []
      console.log(sendCode,'sendCode')
      return {
        ...initialValues,
        approvalSteps: roleCodes.map(code => ({ approvalRole: code })),
        copySteps:sendCode.map(code => ({ copyNode: code }))
      };
    }
    return initialValues;
  }, [initialValues]);

  return (
    <ProForm
      initialValues={processedInitialValues}
      onFinish={run}
      key={processedInitialValues?.id}
    >
      {/* Rule Name */}
      <ProFormText name="flowName" label="规则名称" rules={[{ required: true }]} />
      {/* Condition Section */}

      <ProFormSelect
          hidden={true}
            name="flowType"
            label="规则类型"
            
            options={[
              // { label: '设置价格', value: 1 },
              { label: '修改金额', value: 2 },
              // { label: '申请退款', value: 3 },
            ]}
            placeholder="请选择位置"
            // rules={[{ required: true, message: '请选择位置' }]}
          />

      {/* 使用 shouldUpdate 来控制条件部分的显示 */}
      <ProForm.Item shouldUpdate={(prevValues, currentValues) => prevValues.flowType !== currentValues.flowType}>
        {(form) => {
          const flowType = form.getFieldValue('flowType');
          if (flowType === 3) { // 3 代表退款
            return null;
          }
          return (
            <ProFormGroup >
              {/* <ProFormSelect
                name="conditions"
                label="当改价后的价格与原价的差值"
                valueEnum={{
                  greaterThan: '大于',
                  lessThan: '小于',
                  equal: '等于',
                }}
                rules={[{ required: true }]}
              /> */}
           <ProFormDigit 
            name="price"
            label="价格折扣大于等于"
            rules={[
              { 
                required: true,
                validator: async (_, value) => {
                  if (value === undefined || value === null || value === '') {
                    throw new Error('请输入价格折扣');
                  }
                  if (value < 0 || value > 10) {
                    throw new Error('请输入0-10之间的数字，最多两位小数');
                  }
                  // 检查小数位数
                  const decimalPlaces = value.toString().split('.')[1]?.length || 0;
                  if (decimalPlaces > 2) {
                    throw new Error('最多支持两位小数');
                  }
                  return Promise.resolve();
                }
              }
            ]}
            fieldProps={{

              addonAfter: '折',
            }}
            />
            </ProFormGroup>
          );
        }}
      </ProForm.Item>

      {/* Approval Process */}
      <ProFormList
        name="approvalSteps"
        label="审批流程如下"
        copyIconProps={false} // Hide the copy button
        creatorButtonProps={{
          position: 'bottom',
          creatorButtonText: '新增审批节点',
        }}
      >
        <ProFormGroup>
          <ProFormSelect
            name="approvalRole"
            label="审批节点"
            request={async () => role}
            style={{ width: '300px' }}
          />
        </ProFormGroup>
      </ProFormList>
      
      <ProFormList
        name="copySteps"
        label="抄送节点"
        copyIconProps={false} // Hide the copy button
        creatorButtonProps={{
          position: 'bottom',
          creatorButtonText: '新建抄送节点',
        }}
      >
        <ProFormGroup>
          <ProFormSelect
            name="copyNode"
            label=""
            request={async () => role}
            style={{ width: '300px' }}
          />
        </ProFormGroup>
      </ProFormList>
    </ProForm>
  );
};

export default AuditConfigForm;